class Seiso::ImportMaster
  # Author:: Willie Wheeler
  # Copyright:: Copyright (c) 2014-2016 Expedia, Inc.
  # License:: Apache 2.0
  class Mappers::NodeIpAddressMapper

    def initialize(api)
      @api = api
      @ipr_search_resource = api.ipAddressRoles.search.get
    end

    def map(doc_nip, context)
      node = context['node']
      si_key = context['serviceInstance'].body['key']
      ipr_name = doc_nip['ipAddressRole']
      ip_addr = doc_nip['ipAddress']

      # TODO Verify that the API assigns the rotationStatus and aggregateRotationStatus to "unknown" in the POST case.
      # See node_mapper.rb
      {
        'node' => node.links.self.href,
        # Can't use UriResolver here since ipr requires two keys.
        'ipAddressRole' => to_ip_address_role(si_key, ipr_name).links.self.href,
        'ipAddress' => ip_addr
      }
    end

    private

    def to_ip_address_role(si_key, ipr_name)
      search_params = { 'si' => si_key, 'name' => ipr_name }

      # TODO Handle 404. But shouldn't get them if the data is good, so
      # make sure we're importing the IP address roles before the nodes.
      @ipr_search_resource.findByServiceInstanceKeyAndName(search_params).get
    end
  end
end
